const express = require('express');
const db = require("../db");
const router = express.Router();

router.get('/getProjectList',  (req, res) => {
    const sql = 'SELECT * FROM project';
    db.query(sql, (err, results) => {
        if (err) {
            return res.send({ 
                status: 500, 
                data: { message: '获取项目列表失败', error: err.message } 
            });
        }
        
        res.send({ 
            status: 200, 
            data: { 
                message: '获取项目列表成功', 
                projects: results 
            } 
        });
    });
});
router.post('/addViewsForProject', (req, res) => {
    const { id } = req.body;
    if (!id) {
        return res.send({ 
            status: 400, 
            data: { message: '项目ID不能为空' } 
        });
    }

    // 检查项目是否存在
    const checkSQL = 'SELECT id FROM project WHERE id = ?';
    db.query(checkSQL, [id], (err, results) => {
        if (err) {
            return res.send({ 
                status: 500, 
                data: { message: '检查项目失败', error: err.message } 
            });
        }
        if (results.length === 0) {
            return res.send({ 
                status: 404, 
                data: { message: '项目不存在' } 
            });
        }

        // 更新项目的views字段
        const updateSQL = 'UPDATE project SET views = views + 1 WHERE id = ?';
        db.query(updateSQL, [id], (err, results) => {
            if (err) {
                return res.send({ 
                    status: 500, 
                    data: { message: '更新项目失败', error: err.message } 
                });
            }
            res.send({ 
                status: 200, 
                data: { message: '项目视图增加成功' } 
            });
        });
    });
});
module.exports = router;
